package com.yyq.eduservice.lisenner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyq.eduservice.entity.EduSubject;
import com.yyq.eduservice.entity.excel.excelData;
import com.yyq.eduservice.service.EduSubjectService;
import com.yyq.servicebase.exceptionhandler.YyqException;

/**
 * @author yyq
 * @create 2021-04-14 23:51
 * 由于没法注入Spring管理
 * 所以需要传service到这里
 */
public class excelLisenner extends AnalysisEventListener<excelData> {
    //一行一行读excel中的数据
    public EduSubjectService subjectService;
    excelLisenner(){}
    public excelLisenner(EduSubjectService subjectService){
        this.subjectService=subjectService;
    }
    @Override
    public void invoke(excelData excelData, AnalysisContext analysisContext) {
        if(excelData==null){     //Excel表格为空抛出异常
            throw new YyqException();
        }
        EduSubject firstSubjectExist=existFirstSubject(excelData.getOneSubjectName()); //检查 例如 后端 是否存在
        if(firstSubjectExist==null){   //不存在肯定要保存到数据库了
            firstSubjectExist=new EduSubject();
            String title=excelData.getOneSubjectName();  //设置数据库实体类各种数据
            firstSubjectExist.setTitle(title);
            firstSubjectExist.setParentId("0");
            firstSubjectExist.setSort(0);
            subjectService.save(firstSubjectExist);  //保存到数据库
        }
        String parentpid= firstSubjectExist.getId();  // 如果数据库中没有这个数据 输入数据库后自动创建ID
        //如果有则直接读
        EduSubject secSubjectExist=existSecSubject(excelData.getTwoSubjectName(),parentpid);
        if(secSubjectExist==null){
            secSubjectExist=new EduSubject();
            String title=excelData.getTwoSubjectName();
            secSubjectExist.setTitle(title);
            secSubjectExist.setParentId(parentpid);
            secSubjectExist.setSort(0);
            subjectService.save(secSubjectExist);
        }
    }

    private EduSubject existSecSubject(String twoSubjectName, String parentpid) {
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",twoSubjectName);
        wrapper.eq("parent_id",parentpid);
        EduSubject two = subjectService.getOne(wrapper);
        return two;

    }

    private EduSubject existFirstSubject(String oneSubjectName) {
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",oneSubjectName);
        wrapper.eq("parent_id","0");
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
